#include <iostream>
#include <queue>
#include <pthread.h>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include "BlockQueue.hpp"
#include "Task.hpp"
const std::string oper = "+-*/%";
int myMath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            std::cerr << "Error: div zero!" << std::endl;
            result = -1;
        }
        else
            result = x / y;
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cerr << "Error: mod zero!" << std::endl;
            result = -1;
        }
        else
            result = x % y;
    }
    break;
    default:
        break;
    }
    return result;
}
// 生产者
void *productor(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (1)
    {
        // 生产数据
        int x = rand() % 10 + 1;
        int y = rand() % 5;
        int operIndex = rand() % oper.size();
        Task t(x, y, oper[operIndex], myMath);
        bq->push(t); // 把任务push进阻塞队列
        printf("Production task:%s\n", t.toString().c_str());
        sleep(1);
    }
    return nullptr;
}
// 消费者
void *consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (1)
    {
        // 消费数据
        Task t;
        bq->pop(&t);
        printf("Consumed task:%s\n", t().c_str());// operator()
        // sleep(1);
    }
    return nullptr;
}
int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    pthread_t c, p;
    pthread_create(&c, nullptr, consumer, bq);
    pthread_create(&p, nullptr, productor, bq);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);
    delete bq;
    return 0;
}